package redis

import (
	"context"
	"net"

	"gitee.com/zacyuan/yuan/pkg/log"
	"github.com/redis/go-redis/v9"
)

type LogHook struct {
}

func NewLogHook() *LogHook {
	return &LogHook{}
}

func (LogHook) DialHook(next redis.DialHook) redis.DialHook {
	return func(ctx context.Context, network, addr string) (net.Conn, error) {
		conn, err := next(ctx, network, addr)
		log.FormContext(ctx).Infof("Connect redis:[%s-%s]", network, addr)
		return conn, err
	}
}

func (LogHook) ProcessHook(next redis.ProcessHook) redis.ProcessHook {
	return func(ctx context.Context, cmd redis.Cmder) error {
		err := next(ctx, cmd)
		log.FormContext(ctx).Infof("cmd:[%s] args:[%v] error:[%v]", cmd.String(), cmd.Args(), err)
		return err
	}
}

func (LogHook) ProcessPipelineHook(next redis.ProcessPipelineHook) redis.ProcessPipelineHook {
	return func(ctx context.Context, cmds []redis.Cmder) error {
		err := next(ctx, cmds)
		for _, cmd := range cmds {
			log.FormContext(ctx).Infof("cmd:%v", cmd.Args())
		}
		log.FormContext(ctx).Info("%v", err)
		return err
	}
}
